package geektime;

import io.smallrye.mutiny.Uni;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.util.concurrent.Executor;
import java.util.concurrent.ForkJoinPool;

/**
 * @Author chenlin
 * @Date 2022/3/16 22:34
 * @Description //TODO
 */
public class WeatherService {

    private WeatherProperties properties;

    private static Executor executor = new ForkJoinPool();

    public WeatherService() {
    }

    public WeatherService(WeatherProperties properties) {
        this.properties = properties;
    }

    public String printCity() {
        return "当前城市： " + properties.city();
    }

    public String getCityWeather() {
        return getWeatherByCity(properties.city());
    }

    public String getCityWeather2(String city) {
        return getWeatherByCity(city);
    }

    public Uni<String> getCityWeather(String city) {
      return Uni.createFrom().item(getWeatherByCity(city)).onFailure().recoverWithItem(ex-> "查询失败");
    }

    public String getWeatherByCity(String city){
        String ret = null;
        try {
            String url = "http://wthrcdn.etouch.cn/weather_mini?city=" + city;
            OkHttpClient okHttpClient = new OkHttpClient();
            final Request request = new Request.Builder()
                    .url(url)
                    .build();
            final Call call = okHttpClient.newCall(request);
            Response response = null;
            response = call.execute();
            ret = response.body().string();
            System.out.println(ret);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

}
